package com.bblocks.dbmonitor.config;

import com.bblocks.dbmonitor.annotation.MonitorTable;
import jodd.util.StringPool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import top.javatool.canal.client.client.CanalClient;

import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>Project: bblocks-pro - MonitorTableManager</p>
 * <p>描述：收集表对应的 相关服务（MonitorTable标记)</p>
 *
 * @Author Zhao [125043150@qq.com]
 * @Date 2024/1/16 11:39
 * @Version 1.0
 * @since 8
 */
@Slf4j
@RequiredArgsConstructor
public class MonitorTableManager implements InitializingBean {

    private final ApplicationContext applicationContext;

    private Map<String, MonitorTableServiceInfo> monitorTableServiceMap = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() {
        // 获取所有实现了该接口的bean
        String[] allBeanNames = applicationContext.getBeanDefinitionNames();;
        for (String beanName : allBeanNames) {
            Object bean =  applicationContext.getBean(beanName);

            MonitorTable monitorTable = AnnotationUtils.findAnnotation(bean.getClass(), MonitorTable.class);
            if (monitorTable != null) {
                CacheConfig cacheConfig = AnnotationUtils.findAnnotation(bean.getClass(), CacheConfig.class);
                MonitorTableServiceInfo monitorTableService = MonitorTableServiceInfo
                        .builder()
                        .monitorTable(monitorTable)
                        .cacheNames(cacheConfig != null ? cacheConfig.cacheNames():null)
                        .recordChangedBaseBean(bean)
                        .build();
                monitorTableServiceMap.put(monitorTable.value(),monitorTableService);
            }
        }

        log.info("dbmonitor 启动完成！");
    }

    @PreDestroy
    public void destroy(){
        monitorTableServiceMap.clear();
    }

    /**
     * 提取服务对象
     * 1、根据dbName+"."+tableName
     * 2、以上提取不到再 tableName 提取一次
     * @param dbName
     * @param tableName
     * @return
     */
    public MonitorTableServiceInfo getMonitorTableService(String dbName,String tableName){
        MonitorTableServiceInfo monitorTableServiceInfo = monitorTableServiceMap.get(dbName + MonitorTable.DOT + tableName);
        if(monitorTableServiceInfo != null)
            return monitorTableServiceInfo;

        return monitorTableServiceMap.get(tableName);
    }
}
